using System;
using Engine;
using Engine.Graphics;

namespace RuthlessConquest {
    public class ParticlesModule : Module {
        public DynamicArray<ParticleSystemBase> publicParticleSystems = new();

        public DynamicArray<ParticleSystemBase> TmpParticleSystemList = new();

        public ReadOnlyList<ParticleSystemBase> ParticleSystems => new(publicParticleSystems);

        public ParticlesModule(Game game) : base(game) { }

        public void AddParticleSystem(ParticleSystemBase particleSystem) {
            if (particleSystem.Game != null) {
                throw new InvalidOperationException();
            }
            publicParticleSystems.Add(particleSystem);
            particleSystem.Game = Game;
        }

        public void RemoveParticleSystem(ParticleSystemBase particleSystem) {
            if (particleSystem.Game != Game) {
                throw new InvalidOperationException();
            }
            publicParticleSystems.Remove(particleSystem);
            particleSystem.Game = null;
        }

        public void Draw(Color colorTransform, int layer) {
            TmpParticleSystemList.Clear();
            foreach (ParticleSystemBase publicParticleSystem in publicParticleSystems) {
                if (publicParticleSystem.Layer == layer) {
                    TmpParticleSystemList.Add(publicParticleSystem);
                }
            }
            foreach (ParticleSystemBase tmpParticleSystem in TmpParticleSystemList) {
                if (tmpParticleSystem.Run(Time.FrameDuration)) {
                    RemoveParticleSystem(tmpParticleSystem);
                }
                else {
                    tmpParticleSystem.Draw(CameraModule, colorTransform);
                }
            }
            CameraModule.PrimitivesRenderer.Flush(CameraModule.WorldToScreenMatrix * PrimitivesRenderer2D.ViewportMatrix());
        }
    }
}